package com.kuaidu.ll.quickreadnews.net;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.kuaidu.ll.quickreadnews.QRNewsApp;
import com.kuaidu.ll.quickreadnews.configs.KDConfig;
import com.kuaidu.ll.quickreadnews.configs.KDUrlConfigs;

import java.io.File;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2017/7/19.
 */
public class RetrofitManager {
    private static volatile RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private static String BEGINBASEURL = KDUrlConfigs.KDBASEURL;

    private RetrofitManager() {
        initRetrofit();
    }

    public void initRetrofit() {
        initRetrofit(KDUrlConfigs.KDBASEURL);
    }

    public void initRetrofit(String baseUrl) {
        if (TextUtils.isEmpty(baseUrl)){
            return;
        }
        if (retrofit == null) {
            createRetrofir(baseUrl);
        }
//        else if (retrofit != null && !BEGINBASEURL.equals(baseUrl)) {
//            createRetrofir(baseUrl);
//            BEGINBASEURL = baseUrl;
//        }
    }

    private void createRetrofir(String baseUrl) {
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(getGson()))
                .client(getDefualtOkhttp())
                .build();
    }


    public static RetrofitManager getInstance() {
        if (retrofitManager == null) {
            synchronized (RetrofitManager.class) {
                if (retrofitManager == null) {
                    retrofitManager = new RetrofitManager();
                }
            }
        }
        return retrofitManager;
    }

    public Gson getGson() {
        return new GsonBuilder()
                .serializeNulls()
                .enableComplexMapKeySerialization()
                .create();
    }

    /**
     * 开启缓存
     */
    private OkHttpClient getDefualtOkhttp() {
        return new OkHttpClient.Builder()
//                //开启缓存
//                .cookieJar(new CookieManger(BaseApp.getInstance()))
//                .cache(getResponseCache())
                .addInterceptor(new HttpLoggingInterceptor())
//                //添加缓存拦截
//                .addNetworkInterceptor(new CacheInterceptor())
                .build();
    }
    private Cache getResponseCache(){
        File cacheFile = QRNewsApp.mApp.getExternalCacheDir();
        return new Cache(cacheFile, KDConfig.DEFAULT_RESPONSE_CACHE_SIZE);
    }
}
